import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'; 
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '*',
    redirect: '/goods'
  },
  {
    name: 'home',
    component: HomeView
  },
  {
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    name: 'user',
    component: () => import('@/views/user'),
    meta: {
      title: '会员中心',
      parentRoute: '#'
    }
  },
  {
    name: 'cart',
    component: () => import('@/views/cart'),
    meta: {
      title: '购物车',
      parentRoute: '#12'
    }
  },
  {
    name: 'goods',
    component: () => import('@/views/goods'),
    meta: {
      title: '商品详情',
      parentRoute: '#'
    }
  }
]

// add route path
routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '');
});

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const title = to.meta && to.meta.title;
  const parentRoute = to.meta && to.meta.parentRoute;
  if (title) {
    document.title = title;
    store.dispatch('updatePageTitle', to.meta.title);  
  }else {  
    store.dispatch('updatePageTitle', '一站式服务大厅');  
  };
  if (parentRoute) {
    store.dispatch('updateParentRoute', to.meta.parentRoute);  
  }else {  
    store.dispatch('updateParentRoute', '#');  
  } 
  next();
});

export default router
